'''
Created on Nov 19, 2010

@author: dexen
'''

import time
import multiprocessing as mp


from dexen.system.common.meta import JobMeta
from dexen.system.node.slave.comm import InUnit, OutUnit
from dexen.system.common.transact import SlaveRecvTransact
from dexen.system.node.slave.executor import SlaveTaskExecutor



#===============================================================================
# SlaveCore
#===============================================================================
class SlaveCore(mp.Process):
    def __init__(self, comm):
        mp.Process.__init__(self)
        self.comm = comm
        self.executors = {} # job_id:SlaveTaskExecutor

    def _update_jobs(self):
        job_metas = self.comm.get_jobs()
        for job_meta in job_metas:
            assert isinstance(job_meta, JobMeta)
            self.executors[job_meta.get_id()] = SlaveTaskExecutor(job_meta)
            print "slave.core I have created executor for ", job_meta.get_id(), job_meta.get_name()

    def _get_executor(self, unit):
        assert isinstance(unit, InUnit)
        print "checking if executor has key", unit.job_id 
        assert self.executors.has_key(unit.job_id)
        return self.executors[unit.job_id]

    def _update_transact(self):
        unit = self.comm.get_in_unit()
        if unit != None:
            task_executor = self._get_executor(unit)    
            assert isinstance(task_executor, SlaveTaskExecutor)
            transact = task_executor.execute(unit)
            assert isinstance(transact, SlaveRecvTransact)
            job_id = task_executor.get_job_id()
            self.comm.set_out_unit(OutUnit(job_id, transact))
        
    def run(self):
        while True:
            self._update_jobs()
            self._update_transact()
            time.sleep(1)
    
